package com.lai.gulimall.order.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lai.common.constant.OrderConstant;
import com.lai.common.exception.BizCodeEnum;
import com.lai.common.exception.RRException;
import com.lai.common.to.OrderItemTo;
import com.lai.common.to.SkuHasStockTo;
import com.lai.common.to.SkuLockStockResultTo;
import com.lai.common.to.WareSkuLockTo;
import com.lai.common.utils.R;
import com.lai.common.vo.MemberRespVo;
import com.lai.gulimall.order.entity.OrderItemEntity;
import com.lai.gulimall.order.feign.CartFeignService;
import com.lai.gulimall.order.feign.MemberFeignService;
import com.lai.gulimall.order.feign.ProductFeignService;
import com.lai.gulimall.order.feign.WareFeignService;
import com.lai.gulimall.order.interceptor.OrderInterceptor;
import com.lai.gulimall.order.service.OrderItemService;
import com.lai.gulimall.order.to.OrderCreateTo;
import com.lai.gulimall.order.to.SpuInfoTo;
import com.lai.gulimall.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lai.common.utils.PageUtils;
import com.lai.common.utils.Query;

import com.lai.gulimall.order.dao.OrderDao;
import com.lai.gulimall.order.entity.OrderEntity;
import com.lai.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitThreadLocal = new ThreadLocal();

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public OrderSettleVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderSettleVo orderSettleVo = new OrderSettleVo();
        MemberRespVo memberRespVo = OrderInterceptor.loginUser.get();
        Long memberId = memberRespVo.getId();

        //获取当前线程上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1、远程查询所有的收货地址列表
        CompletableFuture<Void> receiveAddressFuture = CompletableFuture.runAsync(() -> {
            //把主线程上下文设置到这个异步线程里
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R receiveAddressEntityList = memberFeignService.getReceiveAddressByMemberId(memberId);
            if (receiveAddressEntityList.getCode() == 0) {
                ArrayList<MemberReceiveAddressVo> memberReceiveAddressVo = receiveAddressEntityList.getData(new TypeReference<ArrayList<MemberReceiveAddressVo>>() {
                });
                orderSettleVo.setReceiveAddress(memberReceiveAddressVo);
            } else {
                throw new RRException(BizCodeEnum.FEIGN_EXCEPTION.getMsg(), BizCodeEnum.FEIGN_EXCEPTION.getCode());
            }
        }, executor);
        //2、远程查询所有购物车中  选中的购物项
        CompletableFuture<Void> cartItemFuture = CompletableFuture.runAsync(() -> {
            //把主线程上下文设置到这个异步线程里
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //根据用户id重新获取购物车数据
            R cartItemVoList = cartFeignService.getUserCartItemsById(memberId);
            if (cartItemVoList.getCode() == 0) {
                ArrayList<OrderItemVo> cartItemList = cartItemVoList.getData(new TypeReference<ArrayList<OrderItemVo>>() {
                });
                orderSettleVo.setOrderItem(cartItemList);
            } else {
                throw new RRException(BizCodeEnum.FEIGN_EXCEPTION.getMsg(), BizCodeEnum.FEIGN_EXCEPTION.getCode());
            }
        }, executor).thenRunAsync(()->{
            //远程查询   收集到购物车里所有的商品id   批量查询是否有货
            List<Long> skuIds = orderSettleVo.getOrderItem().stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            if(skusHasStock.getCode() == 0){
                List<SkuHasStockTo> data = skusHasStock.getData(new TypeReference<List<SkuHasStockTo>>() {
                });
                if(data != null) {
                    //把list转换成map  skuid（Long） stock（boolean）  查询某个skuid是否有库存
                    Map<Long, Boolean> skuIdHasStock = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                    orderSettleVo.setStocks(skuIdHasStock);
                }
            }
        },executor);

        //3、查询优惠券（用户积分）信息
        orderSettleVo.setIntegration(memberRespVo.getIntegration());

        //TODO 4、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId() , token , 30 , TimeUnit.MINUTES);
        orderSettleVo.setOrderToken(token);

        //等待所有任务完成后在return
        CompletableFuture.allOf(receiveAddressFuture,cartItemFuture).get();

        return orderSettleVo;
    }


    //订单提交步骤
    //1、 验证令牌  -> 2、构建订单项  -> 3、构建全部订单项  -> 4、计算优惠、积分、价格等信息  -> 5、构建订单  -> 6、保存订单
    @Transactional  //在代码执行出错的时候能够进行事务的回滚
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo orderSubmitVo) {
        OrderSubmitRespVo orderSubmitRespVo = new OrderSubmitRespVo();

        //把orderSubmitVo放入threadLocal里
        orderSubmitThreadLocal.set(orderSubmitVo);

        MemberRespVo memberRespVo = OrderInterceptor.loginUser.get();
        //1、验证令牌（令牌的对比和删除必须保证原子性） 课使用lua脚本
        //0 验证失败    1  验证成功   把orderToken和redisTokenKey进行对比，对比验证通过返回1，反之返回0
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //浏览器传入的token
        String orderToken = orderSubmitVo.getOrderToken();
        //redis中的token的key
        String redisTokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                , Arrays.asList(redisTokenKey), orderToken);
        if(result == 1L){
            //1、验证令牌成功  则创建订单
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if( Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //金额对比成功
                //3、保存订单
                saveOrder(order);
                //4、锁定库存  接入事务Transactional
                WareSkuLockTo wareSkuLockTo = new WareSkuLockTo();
                wareSkuLockTo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemTo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemTo orderItemTo = new OrderItemTo();
                    orderItemTo.setSkuId(item.getSkuId());
                    orderItemTo.setCount(item.getSkuQuantity());
                    orderItemTo.setTitle(item.getSkuName());
                    return orderItemTo;
                }).collect(Collectors.toList());
                wareSkuLockTo.setLocks(collect);
                // TODO 远程锁库存
                R r = wareFeignService.orderLockStock(wareSkuLockTo);
                if(r.getCode() == 0){
                    //库存锁定成功
                    SkuLockStockResultTo data = r.getData(new TypeReference<SkuLockStockResultTo>() {
                    });
                    if(data.getLocked()){
                        orderSubmitRespVo.setCode(OrderConstant.OrderSubmitEnum.SUCCESS.getCode());
                        orderSubmitRespVo.setOrder(order.getOrder());
                        return orderSubmitRespVo;
                    }else{
                        //库存锁定失败
                        orderSubmitRespVo.setCode(OrderConstant.OrderSubmitEnum.STOCK_LOCK_ERROR.getCode());
                        throw new RRException(BizCodeEnum.FEIGN_EXCEPTION);
                    }
                }else {
                    //库存锁定失败
                    orderSubmitRespVo.setCode(OrderConstant.OrderSubmitEnum.STOCK_LOCK_ERROR.getCode());
                    throw new RRException(BizCodeEnum.FEIGN_EXCEPTION);
                }

            }else{
                //金额对比失败
                orderSubmitRespVo.setCode(OrderConstant.OrderSubmitEnum.PRICE_ERROR.getCode());
                return orderSubmitRespVo;
            }
        }else{
            //验证令牌失败
            orderSubmitRespVo.setCode(OrderConstant.OrderSubmitEnum.TOKEN_VERIFY_ERROR.getCode());
            return orderSubmitRespVo;
        }
    }

    /**
     * 保存订单
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //订单
        OrderEntity order = orderCreateTo.getOrder();
        //订单项
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //保存订单
        baseMapper.insert(order);
        //批量保存订单项
        orderItemService.saveBatch(orderItems);

    }


    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        OrderSubmitVo orderSubmitVo = orderSubmitThreadLocal.get();
        MemberRespVo memberRespVo = OrderInterceptor.loginUser.get();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //2、构建订单
        OrderEntity orderEntity = buildOrder(orderSubmitVo.getAddressId(),memberRespVo, orderSn);
        //3、构建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(memberRespVo.getId(), orderSn);
        //4、计算价格  积分 等相关信息
        computePrice(orderEntity,orderItemEntities);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    /**
     * 计算价格
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        // TODO 优惠券抵扣金额
        BigDecimal coupon = new BigDecimal("0.0");
        //积分抵扣金额
        BigDecimal integrationAmount = new BigDecimal("0.0");
        //促销优化金额（促销价、满减、阶梯价）
        BigDecimal promotion = new BigDecimal("0.0");
        //赠送积分
        BigDecimal giftIntegration = new BigDecimal("0.0");
        //赠送成长值
        BigDecimal giftGrowth = new BigDecimal("0.0");

        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integrationAmount = integrationAmount.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            total = total.add(orderItemEntity.getRealAmount());
            giftIntegration = giftIntegration.add(new BigDecimal(orderItemEntity.getGiftIntegration().toString()));
            giftGrowth = giftGrowth.add(new BigDecimal(orderItemEntity.getGiftGrowth().toString()));
        }
        //设置运费
        orderEntity.setFreightAmount(new BigDecimal("0.0"));
        //商品总价
        orderEntity.setTotalAmount(total);
        //应付总额   总价 + 运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //积分   成长值
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());
        //设置 积分抵扣金额   促销优化金额（促销价、满减、阶梯价）  赠送积分   赠送成长值
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integrationAmount);
        orderEntity.setPromotionAmount(promotion);
    }

    /**
     * 构建订单
     *
     * @param memberRespVo
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(Long addressId, MemberRespVo memberRespVo, String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        orderEntity.setMemberUsername(memberRespVo.getUsername());
        orderEntity.setCreateTime(DateUtil.date());
        //订单来源[0->PC订单；1->app订单]
        orderEntity.setSourceType(0);
        //订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单】
        orderEntity.setStatus(0);
        //自动确认时间（天）
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0);
        //2、获取用户的收货地址
        R info = memberFeignService.info(addressId);
        if(info.getCode() == 0){
            MemberReceiveAddressVo data = info.getData(new TypeReference<MemberReceiveAddressVo>() {
            });
            //设置收货人信息
            orderEntity.setReceiverName(data.getName());
            orderEntity.setReceiverPhone(data.getPhone());
            orderEntity.setReceiverProvince(data.getProvince());
            orderEntity.setReceiverCity(data.getCity());
            orderEntity.setReceiverRegion(data.getRegion());
            orderEntity.setReceiverDetailAddress(data.getDetailAddress());
            orderEntity.setReceiverPostCode(data.getPostCode());
            return orderEntity;
        }else {
            throw new RRException(BizCodeEnum.FEIGN_EXCEPTION.getMsg(),BizCodeEnum.FEIGN_EXCEPTION.getCode());
        }
    }


    /**
     * 构建所有订单项
     * @param memberId
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(Long memberId,String orderSn){
        //最后一次查询购物车的 商品价格   确保是最新的价格
        R userCartItemsById = cartFeignService.getUserCartItemsById(memberId);
        if(userCartItemsById.getCode() == 0){
            //List<CartItemVo>
            List<OrderItemVo> data = userCartItemsById.getData(new TypeReference<List<OrderItemVo>>() {
            });
            if(data.size() > 0 && data != null){
                List<OrderItemEntity> collect = data.stream().map(orderItemVo -> {
                    OrderItemEntity orderItemEntity = buildOrderItem(orderItemVo);
                    orderItemEntity.setOrderSn(orderSn);
                    return orderItemEntity;
                }).collect(Collectors.toList());
                return collect;
            }
            return null;
        }else{
            throw new RRException(BizCodeEnum.FEIGN_EXCEPTION.getMsg(),BizCodeEnum.FEIGN_EXCEPTION.getCode());
        }
    }


    /**
     * 构建某个订单项
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo){
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息
        //2、商品的spu信息
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(orderItemVo.getSkuId());
        if(spuInfoBySkuId.getCode() == 0){
            SpuInfoTo spuInfoTo = spuInfoBySkuId.getData(new TypeReference<SpuInfoTo>() {
            });
            orderItemEntity.setSpuId(spuInfoTo.getId());
            orderItemEntity.setSpuName(spuInfoTo.getSpuName());
            //TODO 获取spu图片
            //orderItemEntity.setSpuPic();
            orderItemEntity.setSpuBrand(spuInfoTo.getBrandId().toString());
            orderItemEntity.setCategoryId(spuInfoTo.getCatalogId());
            orderItemEntity.setSpuPic(orderItemVo.getImage());
        }else {
            throw new RRException(BizCodeEnum.FEIGN_EXCEPTION);
        }
        //3、商品的sku信息
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        String skuAttr = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        //TODO 4、优惠信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        // 优惠卷  远程查询 coupon
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        //积分优惠  远程查询  member
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //总优惠
        BigDecimal TotalDiscounts = orderItemEntity.getPromotionAmount().add(orderItemEntity.getCouponAmount()).add(orderItemEntity.getIntegrationAmount());
        //TODO 5、积分信息  远程查询用户的会员等级  根据会员等级设置积分
        orderItemEntity.setGiftIntegration(100);
        orderItemEntity.setGiftGrowth(300);
        //6、设置实际价格 = 单价 * 数量 - 各种优惠
        orderItemEntity.setRealAmount(orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())).subtract(TotalDiscounts));

        return orderItemEntity;
    }

}